<!DOCTYPE html>
<html>

<head>
	<meta charset="UTF-8">
	<title>数据源管理</title>
	<meta name="renderer" content="webkit|ie-comp|ie-stand">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
	<meta http-equiv="Cache-Control" content="no-siteapp" />
	<script src="/style/public/publicStyle.js"></script>
	<style type="text/css">
		.layui-table-tool-panel li .layui-form-checkbox[lay-skin=primary] {
			/* width: 100%; */
			padding-left: 28px;
		}、
		.layui-table-tool-panel li {
			line-height: 30px;
			-webkit-transition: .5s all;
			transition: .5s all;
			padding-left: 10px;
			padding-right: 47px;
		}
		td .layui-form-select {
			margin-top: -10px;
			margin-left: -15px;
			margin-right: -15px;
		}
		.layui-table-cell {
			overflow: visible !important;
		}
		.layui-table-view .layui-table th{
			overflow:hidden;
		}
		.layui-table-click {
			background-color:#def0f5;
		}
	</style>
</head>

<body >
<div class="weadmin-nav">
			<span class="layui-breadcrumb" style="visibility: visible;">
			<a href="">任务管理</a><span lay-separator="">/</span>
			<a>
				<cite>任务配置</cite></a>
			</span>
	<a class="layui-btn layui-btn-sm" style="line-height:1.6em;margin-top:3px;float:right" href="javascript:location.replace(location.href);" title="刷新">
		<i class="layui-icon" style="line-height:30px">ဂ</i></a>
</div>

<!--表格-->
<div class="weadmin-body">
	<div class="layui-row">
		<table class="layui-hide" id="tableDataList" lay-filter="mainTableFilter"></table>
	</div>
	<div class="layui-tab">
		<ul class="layui-tab-title">
			<li class="layui-this">表字段</li>
		</ul>
		<div class="layui-tab-content">
			<div class="layui-tab-item layui-show">
				<div class="layui-row">
					<table class="layui-hide" id="fileTable" lay-filter="fieldTableFilter"></table>
				</div>
			</div>
		</div>
	</div>

</div>

<script type="text/html" id="standField" >
	<select name="euTp" lay-filter="stateSelect">
		<option value="STRING">字符串</option>
		<option value="NUMBER">数值型</option>
		<option value="BYTE">二进制</option>
		<option value="DATE">日期</option>
		<option value="TIMESTAMP" >时间戳</option>
	</select>
</script>


<!--表格操作-->
<script type="text/html" id="op">
	<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
	<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="delete">删除</a>
</script>

<!--表格操作-->
<script type="text/html" id="fieldOp">
	<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="remove">删除</a>
</script>
<script type="text/html" id="toolbarDemo">
	<input class="text" style="height:35px;width:257px;" name="" id="hiddenFilter" placeholder="根据表名过滤" />
	<button class="layui-btn layui-btn-sm" lay-event="getCheckData">新增</button>
	<button class="layui-btn layui-btn-sm" lay-event="createTable">建表</button>
</script>

<script type="text/html" id="filedtoolbarDemo">
	<div class="layui-btn-container" id="filedtoolbarDiv">
		<button class="layui-btn layui-btn-sm" lay-event="editField">编辑</button>
	</div>
</script>

<div class="layui-row" id="batchAddTbFld" style="display:none;">
	<div class="layui-btn-container">
		<button type="button" class="layui-btn" lay-demotransferactive="getData">保存</button>
		<button type="button" class="layui-btn" lay-demotransferactive="reload">关闭</button>
	</div>
	<div id="pubFlds" class="demo-transfer" style=""></div>
</div>

<div class="layui-row" id="tableForm" style="display:none;">
	<div class="layui-col-md10">
		<form class="layui-form layui-from-pane" id="formId" style="margin-top:20px" lay-filter="tableForm">
			<input type="hidden" name="idTb"/>
			<div class="layui-form-item">
				<label class="layui-form-label">编码</label>
				<div class="layui-input-block">
					<input type="text" name="cd"  required  lay-verify="required" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">名称</label>
				<div class="layui-input-block">
					<input type="text" name="na"  required  lay-verify="required" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">分类</label>
				<div class="layui-input-block">
					<select name="sdTbca" lay-filter="sdTbca">
						<option value="DW" selected="">DW</option>
						<option value="DM">DM</option>
						<option value="BASE" >BASE</option>
						<option value="DIM" >DIM</option>
					</select>
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">启用标记</label>
				<div class="layui-input-block">
					<select name="fgAct" lay-filter="fgAct">
						<option value=false>删除</option>
						<option value=true selected="">启用</option>
					</select>
				</div>
			</div>
			<div class="layui-form-item" style="margin-top:40px">
				<div class="layui-input-block">
					<button class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="demo11">保存</button>
					<button type="reset" class="layui-btn layui-btn-primary">重置</button>
				</div>
			</div>
		</form>
	</div>
</div>

</body>
<script>
	layui.use(['util','laydate', 'laypage', 'layer', 'table', 'carousel', 'upload', 'element'], function(){
		var util = layui.util;
		var laydate = layui.laydate //日期
            ,transfer = layui.transfer
				,util = layui.util
				,laypage = layui.laypage //分页
				,layer = layui.layer //弹层
				,table = layui.table //表格
				,carousel = layui.carousel //轮播
				,upload = layui.upload //上传
				,element = layui.element //元素操作
				,form = layui.form;
		var logintoken= null;
		//******************************************数据准备*****************************************************
        $.ajax({
            url: '/etl/mdMedPubfld/findByModel',
            type:'get',
            success: function(data1) {
                var data =data1.data; //提出返回数据中的data
                if (data!= null) {
					//显示搜索框
					var arr,allPubFields=[];
					$.each(data, function(index, item) { //循环加入 data的元素
						arr = {
							"value":item.idPubfld,
							"title":item.na+"("+item.idPubfld+")",
							"na":item.na,
							"euTp":item.euTp,
							"numLth":item.numLth,
							"numPrec":item.numPrec
						}
						allPubFields.push(arr);
					});
					transfer.render({
						elem: '#pubFlds'
						,data: allPubFields
						,title: ['公共字段', '已选择']
						,showSearch: true
						,width: 350
						,id: 'key123'
					});
                };
            }
        });

        //******************************************准备完毕*****************************************************
        var batchAddFieldsIndex;
		//批量办法定事件
		util.event('lay-demoTransferActive', {
			getData: function(othis){
				var getData = transfer.getData('key123'); //获取右侧数据
                var tableData = table.cache.fileTable;
                var idPubfldArr=[];
                if(tableData==null) {
                    tableData = [];
                } else {
                    for(var i = 0; i < tableData.length; i++) {
                        idPubfldArr.push(tableData[i].idPubfld);
                    }
				}
                for(var i = 0; i < getData.length; i++) {
                    if($.inArray(getData[i].value,idPubfldArr)==-1) {
                        tableData.push({
                            "idTb":idTb,
                            "idPubfld":getData[i].value,
                            "na":getData[i].na,
                            "euTp":getData[i].euTp,
                            "numLth":getData[i].numLth,
                            "numPrec":getData[i].numPrec,
							"fgAct":1
                        });
					}
				};
                table.reload("fileTable",{data:tableData});
                editFieldButton();
                layer.close(batchAddFieldsIndex);
			}
			,reload:function(){
                layer.close(batchAddFieldsIndex);
			}
		});
        table.render({
            elem: '#tableDataList'
            ,even: false //开启隔行背景
            ,cellMinWidth: 80
            ,toolbar: '#toolbarDemo'
            ,defaultToolbar:[]
            ,url:global_visit_url_prefix+'/etl/mdMedTb/findByPage'
			//,where:{euType:'DW'}
            ,cols: [[
                ,{field:'idTb', title: 'ID', hide:true}
                ,{field:'cd', title: '表名'}
                ,{field:'na', title: '表描述'}
                ,{field:'sdTbca', title: '分类'}
                ,{field:'fgAct', title: '启用标志'}
                ,{field:'des', title: '备注',hide:true}
                ,{field:'naUseCre', title: '创建人',hide:true}
                ,{field:'dtSysCre', title: '创建时间'}
                ,{fixed: 'right', title: '操作', align:'center', toolbar: '#op'}
            ]]
            ,page: true
         });

        $("body").on("keypress","#hiddenFilter",function(event){
            var content = $(this).val();
            if(event.keyCode == '13') {
                //执行重载
                table.reload('tableDataList', {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                    ,where: {
                        filter: content		//在表格中进行搜索
                    }
                });
                $("#hiddenFilter").val(content);
            }
        });
        var fieTableData = layui.table.cache.fileTable;
        table.render({
            elem: '#fileTable'
            ,even: true //开启隔行背景
            ,cellMinWidth: 80
            ,toolbar: '#filedtoolbarDemo'
            ,defaultToolbar:[]
            //,url:'/etl/etlBaseField/find'
            ,cols: [[
                ,{field:'idTbFld', title: 'ID', hide:true}
                ,{field:'idPubfld', title: '字段编码'}
                ,{field:'na', title: '字段名',edit:'text'}
                ,{field:'euTp', title: '字段类型',templet: '#standField'}
                ,{field:'numLth', title: '长度',edit:'text'}
                ,{field:'numPrec', title: '精度',edit:'text'}
                ,{field:'fgAct', title: '启用标志',edit:'text'}
				,{fixed: 'right', title: '操作', align:'center', toolbar: '#fieldOp'}
            ]]
			,done: function (res, curr, count) {
				$(".layui-table-body, .layui-table-box, .layui-table-cell").css('overflow','visible');
                layui.each($("select[name='euTp']"), function (index, item) {
                    var elem = $(item);
                    elem.val(layui.table.cache.fileTable[index].euTp);
                });
                form.render('select');

			}
            ,limit: 1000
            ,page: false
        });
		table.reload("fileTable",{data:[]});
//监听行工具事件
		table.on('tool()', function(obj){ //注：tool 是工具条事件名，mainTableFilter 是 table 原始容器的属性 lay-filter="对应的值"
			var data = obj.data //获得当前行数据
					,layEvent = obj.event; //获得 lay-event 对应的值
			if(layEvent == 'edit'){
				layer.open({
					//layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
					type: 1,
					title: "编辑数据源",
					area: ['820px', '630px'],
					content: $("#tableForm")//引用的弹出层的页面层的方式加载修改界面表单
				});
				//动态向表传递赋值可以参看文章进行修改界面的更新前数据的显示，当然也是异步请求的要数据的修改数据的获取
				setFormValue(obj,data);
			}else if(layEvent == 'delete'){
				layer.confirm('删除表'+data.na+'会级联删除对应的字段，是否继续？', {
					btn: ['继续','取消'], //按钮
				}, function(){
					layer.closeAll('dialog');
					$.ajax({
						type:"get",
						url:"/etl/mdMedTb/delete",
						async:true,
						data:{'idTb':data.idTb},
						success:function(json){
							table.reload("tableDataList");
                            table.reload("fileTable");
						}
					});
				});
			} else if(layEvent=='remove') {
			    var layEvent = $("#filedtoolbarDiv").find(".layui-btn:first-child").attr("lay-event");
			    if("addRapid"==layEvent) {
			        return;
				}
                var oldData = table.cache["fileTable"];
                oldData.splice(obj.tr.data('index'),1);
                table.reload('fileTable',{data : oldData});
                editFieldButton();
			}
		});

		var tableReload = function(tableId) {
            if(idTb!="") {
                $.ajax({
                    url:'/etl/mdMedTbFld/find',
                    type:'get',
                    data:{'idTb':idTb},
                    success:function (msg) {
                        table.reload(tableId,{data:msg.data});
                    }
                })
            } else {
                table.reload(tableId,{data:[]});
			}
		};
		var editFieldButton = function () {
            $("#filedtoolbarDiv").html(
                '<button class="layui-btn layui-btn-sm" lay-event="addField">新增</button>' +
			    '<button class="layui-btn layui-btn-sm" lay-event="saveField">保存</button>' +
			    '<<button class="layui-btn layui-btn-sm" lay-event="returnBack">返回</button>');
        };

//监听表头
		table.on('toolbar()', function(obj){
			var checkStatus = table.checkStatus(obj.config.id);
			switch(obj.event){
				case 'getCheckData':
					layer.open({
						//layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
						type: 1,
						title: "新增数据源",
						area: ['820px', '630px'],
						content: $("#tableForm")//引用的弹出层的页面层的方式加载修改界面表单
					});
					setFormValue(obj,null);
					break;
				case 'createTable':
                    layer.confirm('表存在会被删除，是否继续？', {
                        btn: ['继续','取消'], //按钮
                    }, function(){
                        if(idTb == "") {
                            layer.alert("请先选择表");
                            return;
                        }
                        $.ajax({
                            url: '/etl/mdMedTb/createTable',
                            type:'get',
                            data:{'idTb':idTb},
                            success: function(data1) {
                                layer.alert("表已创建");
                            }
                        });
                    });
				    break;
				case 'addField':
                    batchAddFieldsIndex = layer.open({
                        //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                        type: 1,
                        title: "批量添加表字段",
                        area: ['820px', '630px'],
                        content: $("#batchAddTbFld")//引用的弹出层的页面层的方式加载修改界面表单
                    });
				    break;
				case 'saveField':
				    if(idTb == "") {
                        layer.alert("请先选择表");
                        return;
					}
                    var tableData = table.cache.fileTable;
                    if(tableData.length>0) {
                        $.ajax({
                            url:'/etl/mdMedTbFld/saveList',
                            type:'post',
                            dataType:'json',
                            contentType:'application/json;charset=UTF-8',
                            data:JSON.stringify(tableData),
                            success:function (msg) {
                                table.reload("fileTable",{data:msg.data});
                            }
                        });
					} else {
                        layer.alert("数据不能为空");
					}
                    break;
                case 'editField':
                    if(idTb == "") {
                        layer.alert("请先选择表");
                        return;
                    }
                    editFieldButton();
                    break;
				case 'returnBack':
                    layer.confirm('返回会导致已变更数据的丢失，是否继续？', {
                        btn: ['继续','取消'], //按钮
                    }, function(){
                        layer.closeAll('dialog');
                        tableReload("fileTable");
                    });
                    break;

			};
		});
		var idTb = "";
        //监听行单击事件（双击事件为：rowDouble）
        table.on('row(mainTableFilter)', function(obj){
            var data = obj.data;
            idTb = data.idTb;
            obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');
            tableReload("fileTable");
        });

		//监听弹出框表单提交，massage是修改界面的表单数据'submit(demo11),是修改按钮的绑定
		function setFormValue(obj,data){
			if(data==null) {
				$("#formId")[0].reset();
			} else {
				form.val("tableForm",data);
			}
			form.on('submit(demo11)', function(massage) {
				$.ajax({
					url:'/etl/mdMedTb/save',
					type:'post',
					dataType:'json',
					contentType:'application/json;charset=UTF-8',
					data:JSON.stringify(massage.field),
					success:function (msg) {
                        table.reload("tableDataList");
					}
				})
			})
		}
	});

    layui.use('form',function(){
        var $ = layui.$;
        var form = layui.form;
        $.ajax({
            url: '/etl/baseDb/find',
            type:'get',
			success: function(data1) {
				var data =data1.data; //提出返回数据中的data
                $("#idDbSou").empty();//清空默认值
				if (data!== null) {
				    var flag = true;
					$.each(data, function(index, item) { //循环加入 data的元素
                        $("#idDbSou").append("<option value='"+item.idDb+"'>"+item.na+"</option>");
                        $("#idDbTar").append("<option value='"+item.idDb+"'>"+item.na+"</option>");
                        if(flag) {
                            $("#naDbSou").val(item.na);
                            $("#naDbTar").val(item.na);
                            flag = false;
						}
					});
				};
			}
		});
        $.ajax({
            url: '/etl/etlJb/find',
            type:'get',
            success: function(data1) {
                var data =data1.data; //提出返回数据中的data
                $("#idJb").empty();//清空默认值
                if (data!== null) {
                    var flag = true;
                    $.each(data, function(index, item) { //循环加入 data的元素
                        $("#idJb").append("<option value='"+item.idJb+"'>"+item.na+"</option>");
                    });
                };
            }
        });
        form.render('select');
        $("#naJbcls").val($("#sdJbcls").text().trim());
        form.on('select', function(data){
            var nextId = data.elem.attributes.nextid;
            if(nextId!=null) {
                $("#"+nextId.value).val($(this).text());
			}
        });
        form.on('select(stateSelect)', function (data) {
            var elem = $(data.elem);
            var trElem = elem.parents('tr');
            // 更新到表格的缓存数据中，才能在获得选中行等等其他的方法中得到更新之后的值
            var tableData = layui.table.cache.fileTable;
            tableData[trElem.data('index')][elem.attr('name')] = data.value;
            form.render('select');
        })
    });

</script>

</html>